from django import http
from django.shortcuts import render
from django.views import View
from apps.verifications import constants
from django_redis import get_redis_connection
import random


from utils.response_code import RETCODE


class SMSCodeView(View):
    def get(self, request, mobile):
        # 接受参数request.GET
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验正则

        # 对比图形验证码
         #链接数据库
        image_client = get_redis_connection('verify_image_code')
        # 取出redis的图形验证码
        redis_img_code = image_client.get('img_%s' % uuid)
        if not redis_img_code:
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
        # 删除图形验证码
        image_client.delete('img_%s' % uuid)
        # 对比前段的值
        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})



        # 随机生成验证码  6位
        sms_code ='%06d' % random.randint(0, 999999)
        # 保存到redis  sms_code
        redis_sms_client = get_redis_connection('sms_code')
        send_flag = redis_sms_client.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        # 创建管道
        p1 = redis_sms_client.pipeline()
        p1.setex('sms_%s' % mobile, 300, sms_code)
        p1.setex('send_flag_%s' % mobile, 60, 1)
        p1.execute()
        # 发送短信---容联云
        from celery_tasks.sms.tasks import send_sms_code_ccp
        send_sms_code_ccp.delay(mobile, sms_code)
        print('原始文件的验证码:', sms_code)
        # 返回响应对象

        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})







class ImageCodeView(View):
    def get(self, request, uuid):
        # 接受参数


        # 校验参数 uuid 正则


        # 生成验证码
        from libs.captcha.captcha import captcha
        text, image_code = captcha.generate_captcha()

        # 保存到redis中 为后面发送验证码做准备

        image_client = get_redis_connection('verify_image_code')
        image_client.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 返回响应对象
        return http.HttpResponse(image_code, content_type='image.jpg')